package school.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import school.domain.User;
import school.mapper.UserMapper;
import school.support.BaseController;

@RequestMapping("member")
@Controller
public class MemberController extends BaseController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("index")
    public String index( Model model) {
        model.addAttribute("errorMsg", session.getAttribute("errorMsg"));
        session.removeAttribute("errorMsg");
        if(frontUser() == null) return "redirect:/login";
        return "member";
    }

    /**
     * 更新个人信息
     *
     * @param user
     * @return
     */
    @RequestMapping("update")
    public String update(User user, Model model) {
        user.setId(frontUser().getId());
        userMapper.updateByPrimaryKeySelective(user);
        session.setAttribute("errorMsg", "修改成功");
        session.setAttribute("sessionUser", user);
        return "redirect:index";
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RequestMapping("modfy")
    public String modfy(Model model, String password, String newpassword, String repassword) {
        if (!newpassword.equals(repassword)) {
            session.setAttribute("errorMsg", "两次密码不一样");
            return "redirect:index";
        }
        User user = frontUser();
        if (!user.getPassword().equals(password)) {
            session.setAttribute("errorMsg", "原密码错误");
            return "redirect:index";
        }
        user.setPassword(newpassword);
        userMapper.updateByPrimaryKeySelective(user);
        session.setAttribute("sessionUser", user);
        session.setAttribute("errorMsg", "修改成功");
        return "redirect:index";
    }

}
